package com.zt.service;

import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 统一文件上传服务
 * @author 系统
 * @date 2025/7/23
 */
@Service
@Slf4j
public class FileUploadService {

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.endpoint}")
    private String minioEndpoint;

    // 支持的图片格式
    private static final List<String> ALLOWED_IMAGE_TYPES = Arrays.asList(
            "image/jpeg", "image/jpg", "image/png", "image/gif", "image/webp"
    );

    // 默认桶名
    private static final String DEFAULT_BUCKET = "teacher-manage";
    private static final String AVATAR_BUCKET = "teacher-manager-user-avatar";

    /**
     * 上传头像
     */
    public String uploadAvatar(MultipartFile file) throws Exception {
        return uploadImage(file, AVATAR_BUCKET, "avatars", 5 * 1024 * 1024); // 5MB限制
    }

    /**
     * 上传课程封面
     */
    public String uploadCourseCover(MultipartFile file) throws Exception {
        return uploadImage(file, DEFAULT_BUCKET, "course-covers", 10 * 1024 * 1024); // 10MB限制
    }

    /**
     * 上传科目图标
     */
    public String uploadSubjectIcon(MultipartFile file) throws Exception {
        return uploadImage(file, DEFAULT_BUCKET, "subject-icons", 2 * 1024 * 1024); // 2MB限制
    }

    /**
     * 上传教师头像
     */
    public String uploadTeacherAvatar(MultipartFile file) throws Exception {
        return uploadImage(file, DEFAULT_BUCKET, "teacher-avatars", 5 * 1024 * 1024); // 5MB限制
    }

    /**
     * 上传教师证书
     */
    public String uploadTeacherCertificate(MultipartFile file) throws Exception {
        return uploadImage(file, DEFAULT_BUCKET, "teacher-certificates", 10 * 1024 * 1024); // 10MB限制
    }

    /**
     * 通用图片上传方法
     */
    private String uploadImage(MultipartFile file, String bucket, String folder, long maxSize) throws Exception {
        // 验证文件
        validateFile(file, maxSize);

        try {
            InputStream inputStream = file.getInputStream();
            String fileName = generateFileName(file.getOriginalFilename());
            String objectName = folder + "/" + fileName;

            // 上传到MinIO
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(bucket)
                    .object(objectName)
                    .contentType(file.getContentType())
                    .stream(inputStream, inputStream.available(), -1)
                    .build();

            ObjectWriteResponse response = minioClient.putObject(putObjectArgs);

            if (response != null) {
                // 构建访问URL
                String imageUrl = buildImageUrl(bucket, objectName);
                log.info("文件上传成功: {}", imageUrl);
                return imageUrl;
            }

            throw new RuntimeException("文件上传失败");
        } catch (Exception e) {
            log.error("文件上传异常: {}", e.getMessage(), e);
            throw new RuntimeException("文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 验证文件
     */
    private void validateFile(MultipartFile file, long maxSize) {
        if (file == null || file.isEmpty()) {
            throw new RuntimeException("文件不能为空");
        }

        // 验证文件类型
        String contentType = file.getContentType();
        if (contentType == null || !ALLOWED_IMAGE_TYPES.contains(contentType.toLowerCase())) {
            throw new RuntimeException("只支持上传图片文件 (jpg, jpeg, png, gif, webp)");
        }

        // 验证文件大小
        if (file.getSize() > maxSize) {
            throw new RuntimeException("文件大小不能超过 " + (maxSize / 1024 / 1024) + "MB");
        }
    }

    /**
     * 生成文件名
     */
    private String generateFileName(String originalFilename) {
        String extension = getFileExtension(originalFilename);
        return UUID.randomUUID().toString() + extension;
    }

    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String filename) {
        if (filename == null || filename.lastIndexOf('.') == -1) {
            return "";
        }
        return filename.substring(filename.lastIndexOf('.'));
    }

    /**
     * 构建图片访问URL
     */
    private String buildImageUrl(String bucket, String objectName) {
        // 直接使用MinIO的原始端点
        return minioEndpoint + "/" + bucket + "/" + objectName;
    }
}
